/**
 * 分析API客户端
 * 
 * 用途：与分析服务端进行通信，发送脑波数据并获取分析结果
 * 方法：使用Retrofit进行HTTP通信，支持数据上传和结果查询
 * 原理：
 * - 发送脑波数据到分析服务端进行处理
 * - 轮询获取分析结果
 * - 提供RESTful API接口封装
 */
package com.example.brain_wave.api

import android.util.Log
import com.example.brain_wave.ui.components.BrainWaveDataPoint
import com.example.brain_wave.api.model.TabletBrainWaveRequest
import com.example.brain_wave.api.model.TabletBrainWaveResponse
import com.google.gson.Gson
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import com.example.brain_wave.config.AppConfig
import android.content.Context

/**
 * 发送到分析服务端的数据格式
 */
data class AnalysisDataRequest(
    val session_id: String,
    val room_id: String? = null,
    val user_id: String? = null,
    val timestamp: Long,
    val data: BrainWaveAnalysisData
)

/**
 * 脑波分析数据
 */
data class BrainWaveAnalysisData(
    val delta: Float,
    val theta: Float,
    val alpha: Float,
    val beta: Float,
    val gamma: Float,
    val signal_quality: Float,
    val user_state: String
)

/**
 * 分析结果响应
 */
data class AnalysisResponse(
    val status: String, // no_data, processing, completed, error
    val id: String,
    val message: String,
    val timestamp: Long,
    // processing状态的字段
    val start_time: Long? = null,
    val elapsed_seconds: Double? = null,
    val estimated_completion_seconds: Double? = null,
    val data_count: Int? = null,
    // completed状态的字段
    val sleep_stage: String? = null,
    val confidence: Double? = null,
    val frequency_bands: FrequencyBands? = null,
    val analysis_available: Boolean? = null,
    // error状态的字段
    val error: String? = null,
    val error_time: Long? = null
)

/**
 * 频域功率比例数据（旧版本格式，已弃用）
 */
data class FrequencyBands(
    val delta: Double,
    val theta: Double,
    val alpha: Double,
    val beta: Double,
    val gamma: Double
)

/**
 * 分析状态枚举
 */
enum class AnalysisStatus {
    NO_DATA,
    PROCESSING, 
    COMPLETED,
    ERROR
}

class AnalysisApiClient(private val context: Context) {
    
    private val appConfig = AppConfig.getInstance(context)
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(appConfig.connectTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .writeTimeout(appConfig.writeTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .readTimeout(appConfig.readTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .build()
    
    private val gson = Gson()
    private val mediaType = "application/json; charset=utf-8".toMediaType()
    
    // API配置
    private var baseUrl: String = appConfig.apiBaseUrl // 从配置文件自动读取
    private val dataEndpoint: String get() = appConfig.apiEndpoint
    
    // 回调函数
    private var onDataSent: ((String) -> Unit)? = null
    private var onAnalysisResult: ((TabletBrainWaveResponse) -> Unit)? = null
    private var onError: ((String) -> Unit)? = null
    
    /**
     * 设置API基础URL
     */
    fun setBaseUrl(url: String) {
        baseUrl = url.trimEnd('/')
    }
    
    /**
     * 设置数据发送成功回调
     */
    fun setOnDataSent(callback: (String) -> Unit) {
        onDataSent = callback
    }
    
    /**
     * 设置分析结果回调
     */
    fun setOnAnalysisResult(callback: (TabletBrainWaveResponse) -> Unit) {
        onAnalysisResult = callback
    }
    
    /**
     * 设置错误回调
     */
    fun setOnError(callback: (String) -> Unit) {
        onError = callback
    }
    
    /**
     * 发送脑波数据到分析服务端（使用新的TabletBrainWaveRequest格式）
     */
    fun sendBrainWaveData(
        sessionId: String,
        rawDataPoint: com.example.brain_wave.ui.components.NeuroSkyRawDataPoint,
        roomId: String? = null,
        userId: String? = null
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 直接使用NeuroSkyRawDataPoint的原始数据构造请求
                val requestData = TabletBrainWaveRequest(
                    session_id = sessionId,
                    room_id = roomId ?: "", // 直接使用String类型
                    timestamp = rawDataPoint.timestamp,
                    raw_value = rawDataPoint.rawValues,
                    // 使用NeuroSky的原始功率值
                    delta = rawDataPoint.delta,
                    theta = rawDataPoint.theta,
                    low_alpha = rawDataPoint.lowAlpha,
                    high_alpha = rawDataPoint.highAlpha,
                    low_beta = rawDataPoint.lowBeta,
                    high_beta = rawDataPoint.highBeta,
                    low_gamma = rawDataPoint.lowGamma,
                    mid_gamma = rawDataPoint.midGamma,
                    // NeuroSky算法输出
                    attention = rawDataPoint.attention,
                    meditation = rawDataPoint.meditation,
                    // 信号质量指标
                    poor_signal = rawDataPoint.poorSignal,
                    blink_strength = rawDataPoint.blinkStrength
                )
                
                val json = gson.toJson(requestData)
                val requestBody = json.toRequestBody(mediaType)
                
                val url = "$baseUrl$dataEndpoint"
                println(url)
                val request = Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .build()
                
                println("📤 发送脑波数据到分析服务端: $url")
                println("📊 数据内容: ${json.take(200)}...")
                
                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        val errorMsg = "发送数据失败: ${e.message}"
                        Log.e("AnalysisApiClient", "❌ $errorMsg")
                        onError?.invoke(errorMsg)
                    }
                    
                    override fun onResponse(call: Call, response: Response) {
                        response.use { resp ->
                            if (resp.isSuccessful) {
                                val responseBody = resp.body?.string() ?: ""
                                println("✅ 数据发送成功: ${responseBody.take(100)}...")
                                
                                // 解析新的响应格式
                                try {
                                    val analysisResponse = gson.fromJson(responseBody, TabletBrainWaveResponse::class.java)
                                    println("📊 解析分析结果: success=${analysisResponse.success}, sleepStage=${analysisResponse.sleepStage}")
                                    
                                    // 通知数据发送成功
                                    onDataSent?.invoke(responseBody)
                                    
                                    // 如果包含分析结果，直接回调
                                    if (analysisResponse.success == true && analysisResponse.sleepStage != null) {
                                        onAnalysisResult?.invoke(analysisResponse)
                                    }
                                } catch (e: Exception) {
                                    Log.e("AnalysisApiClient", "❌ 解析响应失败: ${e.message}")
                                    onDataSent?.invoke(responseBody) // 仍然通知发送成功
                                }
                            } else {
                                val errorMsg = "服务器响应错误: ${resp.code} - ${resp.message}"
                                Log.e("AnalysisApiClient", "❌ $errorMsg")
                                onError?.invoke(errorMsg)
                            }
                        }
                    }
                })
                
            } catch (e: Exception) {
                val errorMsg = "发送数据异常: ${e.message}"
                Log.e("AnalysisApiClient", "❌ $errorMsg")
                onError?.invoke(errorMsg)
            }
        }
    }
}